<?php
/**
 * 财务后台手工入账Services
 * User: crstu
 * Date: 2016/6/17
 * Time: 15:34
 */

namespace backend\models\Service;

use common\models\DAO\User;
use common\models\DAO\UserCharge;
use common\models\DAO\UserRemainder;
use common\models\DAO\UserWalletLog;
use yii\helpers\ArrayHelper;

class BookedService
{

    public static function chargeByTradeID($tradeID, $money, $card, $order)
    {
        $user = User::find()->where(['tradeID' => $tradeID])->one();
        if(!empty($user)){
            $transaction = \Yii::$app->getDb()->beginTransaction();
            $userCharge = new UserCharge();
            $userCharge->setScenario('booked');
            $userCharge->userID  = $user->id;
            $userCharge->status  = 1;
            $userCharge->money   = $money*100;
            $userCharge->card    = $card; //卡号
            $userCharge->order   = $order; //银行流水号
            $userCharge->typeID  = 1; //类型：充值
            $userCharge->placeID = 3; //入账方式
            $userCharge->gmID    = \Yii::$app->session->get('ADMIN_ID');
            $userCharge->updateTime = time();
            if($userCharge->save()){
                $userRemainder = new UserRemainder();
                $userRemainder->setScenario('booked');
                $userRemainder->userID  = $user->id;
                $userRemainder->date    = date('Ymd');
                $userRemainder->money   = $money * 100;
                $userRemainder->invest  = $money * 100;
                $userRemainder->typeID  = 1;
                $userRemainder->gmID    = $userCharge->id;
                if($userRemainder->save()){

                    $userWalletLog = new UserWalletLog();
                    $userWalletLog->setScenario('add');
                    $userWalletLog->userID     = $user->id;
                    $userWalletLog->roadID     = 1;
                    $userWalletLog->typeID     = 1;
                    $userWalletLog->money      = $money * 100;
                    $userWalletLog->gmID       = $userCharge->id;

                    if($userWalletLog->save()){
                        $transaction->commit();
                        return [1, '充值成功！'];
                    }else{
                        $transaction->rollBack();
                        return [0, '保存日志失败，入账失败！', $userWalletLog->getFirstErrors()];
                    }
                }else{
                    $transaction->rollBack();
                    return [0, '入账失败', $userRemainder->getFirstErrors()];
                }
            }else{
                return [0, '充值失败！', $userCharge->getFirstErrors()];
            }

        }else{
            return [0, '查无此用户'];
        }
    }

}